package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author tongchen
 * @create 2023-01-27 10:32
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;
    @PostMapping("/upload")
    public R<String>upload(MultipartFile file){
        log.info(file.toString());
        //获取原始文件名，提取JPG
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机文件名
        String random=UUID.randomUUID().toString();
        //获取新名称
        String fileName=random+suffix;
        //创建新名称
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //进行转存
        try {
            log.info("文件路径为"+path+fileName);
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        //输入流，通过提供指定位置去读取数据
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));
            //输出流，通过读取到的数据输出到浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            //将数据通过byte字符数组进行读取
            int len=0;
            byte[]bytes=new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                //刷新
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
